package com.gridpower.spreadsheet.client;

import java.util.LinkedList;
import java.util.Queue;

import com.google.gwt.core.client.GWT;
import com.google.gwt.widgetideas.graphics.client.GWTCanvas;
import com.gridpower.spreadsheet.client.models.AppModel;
import com.gridpower.spreadsheet.client.models.AppModel.TimerListener;
/**
 * this should be a more suitable manager like Service maker
 * @author 438
 *
 */
public class RemoteServiceSequencer {
	
	public static abstract class RemoteCall {
		public void runInSequencer() {
			// lock
			RemoteServiceSequencer.getInstance().getLock();
			// run the call;
			this.run();
			// release lock when the result turn back
			// RemoteServiceSequencer.getInstance().releaseLock();
		}
		public void run() {
			// RemoteServiceSequencer.getInstance().releaseLock();
		}
		
		
	}
	
	boolean lock = false;
	protected  Queue calls = new LinkedList();
	public static RemoteServiceSequencer sequencer =
		new RemoteServiceSequencer();
	
	public RemoteServiceSequencer() {
		AppModel.getInstance().addTimerListener(new TimerListener() {
			public void run() {
				GWT.log("timer", null);
				if (isLocked() == false && calls.size() > 0) {
					RemoteCall call = (RemoteCall)calls.poll();
					call.runInSequencer();
				}
			}
		});
	}
	public static RemoteServiceSequencer getInstance() {
		return sequencer;
	}
	
	public boolean isLocked() {
		return lock;
	}
	public void getLock() {
		lock = true;
	}
	public void releaseLock() {
		lock = false;
	}
	

	public void call(RemoteCall remoteCall) {
		// put to the waitlist
		if (remoteCall != null)
			calls.add(remoteCall);
	}
}
